package com.mobile.check.activitys;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.mobile.check.util.TaskTypeEnum;
import com.mobile.check.zbar.lib.CaptureActivity;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;
import cn.droidlover.xdroidmvp.cache.SharedPref;
import cn.droidlover.xdroidmvp.kit.Kits;
import cn.droidlover.xdroidmvp.kit.NLog;
import cn.droidlover.xdroidmvp.mvp.XActivity;

import com.mobile.check.beans.BluetoothInfo;

import com.mobile.check.app.R;
import com.mobile.check.present.Home2Present;
import com.mobile.check.util.AppContents;
import com.mobile.check.util.S;

import com.mobile.check.dialogs.SubmitTipDialog;

/**
 * 类名: Home2Activity
 * 作者: 李学伟
 * 日期: 2020年10月20日 14:59
 * 描述:
 */
public class Home2Activity extends XActivity<Home2Present> {
    @BindView(R.id.connectDeviceLayout)
    LinearLayout connectDeviceLayout;
    @BindView(R.id.checkTaskLayout)
    LinearLayout checkTaskLayout;
    @BindView(R.id.netTaskLayout)
    LinearLayout netTaskLayout;
    @BindView(R.id.trackTaskLayout)
    LinearLayout trackTaskLayout;
    @BindView(R.id.blueStatusTv)
    TextView blueStatusTv;
    @BindView(R.id.receiveTv)
    TextView receiveTv;
    @BindView(R.id.versionTv)
    TextView versionTv;
    @BindView(R.id.loadingTv)
    TextView loadingTv;


    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        getP().init();
        getP().checkZip();
    }

    @Override
    public void initView() {
        super.initView();
        rightTv.setVisibility(View.VISIBLE);

        titleTv.setText("设备检测");
//        leftIv.setImageResource(R.drawable.setting);
//        leftIv.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                SettingActivity.lunch(Home2Activity.this);
//            }
//        });
        versionTv.setText(Kits.Package.getVersionName(this));
//        rightTv.setText("切换账号");
//        rightTv.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                LoginActivity.lunch(Home2Activity.this);
//            }
//        });
//        trackTaskLayout.setVisibility(View.INVISIBLE);
    }

    @Override
    public void getDataFromServer() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        boolean show = SharedPref.getInstance(this).getBoolean(AppContents.SHOWPOJIE, false);
//        if (show) {
//            trackTaskLayout.setVisibility(View.VISIBLE);
//        } else {
//            trackTaskLayout.setVisibility(View.INVISIBLE);
//        }
    }

    @Override
    public int getContentViewId() {
        return R.layout.activity_home2;
    }

    @Override
    public void getIntentData() {

    }

    @Override
    public Home2Present newP() {
        return new Home2Present();
    }


    @OnClick({R.id.connectDeviceLayout, R.id.scanLayout, R.id.netTaskLayout, R.id.checkTaskLayout,R.id.repeatTaskLayout,R.id.trackTaskLayout, R.id.settingLayout, R.id.dataBackUpLayout, R.id.versionTv})
    public void onViewClicked(View view) {


        if (view.getId() == R.id.scanLayout) {
            if (getP().ishadImportScanBag()) {
                toScan();
            } else {
                if (loadingTv.getVisibility() == View.VISIBLE && loadingTv.getText().toString().contains("数据正在导入")) {
                    showToast("数据正在导入，请稍后！");
                } else {
                    loadingTv.setVisibility(View.VISIBLE);
                    getP().checkScanFile();
                }

            }
            return;

        }
        String userName = SharedPref.getInstance(this).getString(AppContents.USERNAME, "");
        String device = SharedPref.getInstance(this).getString(AppContents.TESTDEVICE, "");
        if (TextUtils.isEmpty(userName) || TextUtils.isEmpty(device)) {
            SubmitTipDialog submitTipDialog = new SubmitTipDialog(this, new SubmitTipDialog.SlectClickListener() {
                @Override
                public void submitClick() {
                    SettingActivity.lunch(Home2Activity.this);
                }

                @Override
                public void cancelClick() {

                }
            });
            submitTipDialog.display("温馨提示", "请完善当前检测人和检测设备后进行。是否设置？", "取消", "设置");
        } else {
            switch (view.getId()) {
                case R.id.connectDeviceLayout:
                    if (!GlobalPoolApplication.instance.isConnect() || GlobalPoolApplication.instance.bluetoothInfo == null) {
                        Intent bluetooth = new Intent(this, BluetoothListActivity.class);
                        startActivityForResult(bluetooth, 0x001);
                    } else {
                        startReceivePage();
                    }
                    break;
                case R.id.checkTaskLayout:
                    TaskListActivity.lunch(this, true, TaskTypeEnum.CHECKTASK);
                    break;
                case R.id.repeatTaskLayout:
                    TaskListActivity.lunch(this, true, TaskTypeEnum.REPEATTASK);
                    break;
                case R.id.trackTaskLayout:
                    TaskListActivity.lunch(this, true, TaskTypeEnum.TRACKTASK);
                    break;
//                case R.id.netTaskLayout:
//                    TaskListActivity.lunch(this, false);
//                    break;
                case R.id.scanLayout:
                    if (getP().ishadImportScanBag()) {
                        toScan();
                    } else {
                        getP().checkScanFile();
                    }
//                    toCreateYh();
                    break;
                case R.id.settingLayout:
                    startActivity(new Intent(this, SettingActivity.class));
                    break;
                case R.id.dataBackUpLayout:
                    getP().exportDatas();
                    break;

                case R.id.versionTv:
                    getP().startimport();
                    break;
            }
        }
    }

    @Override
    public boolean isNotWorkConnect() {
        return false;
    }

    public void toScan() {
        loadingTv.setVisibility(View.GONE);
        startActivityForResult(new Intent(this, CaptureActivity.class), 0x003);
    }

    public void inportFail() {
        loadingTv.setText("数据导入失败，请重新添加检测包。");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        if (requestCode == 0x001) {
            GlobalPoolApplication.instance.bluetoothInfo = data.getParcelableExtra("BluetoothInfo");
            startReceivePage();
        } else if (requestCode == 0x002) {
            if (GlobalPoolApplication.instance.isConnect()) {
                blueStatusTv.setText("已连接");
            } else {
                blueStatusTv.setText("未连接");
            }

        } else if (requestCode == 0x003) {
            String qrCode = data.getStringExtra("QR_CODE");
            NLog.d(TAG, "qrCode=" + qrCode);
            Intent intent = new Intent(this, ScanResultActivity.class);
            intent.putExtra("code", qrCode);
            startActivity(intent);
        }
    }

    private void startReceivePage() {
        Intent intent = new Intent(this, ReceiveDataActivity.class);
        intent.putExtra("BluetoothInfo", GlobalPoolApplication.instance.bluetoothInfo);
        startActivityForResult(intent, 0x002);
    }

    @Override
    protected void onDestroy() {
        GlobalPoolApplication.instance.closeConn();
        getP().ondestory();
        super.onDestroy();
    }

    private void toCreateYh() {

        String imei = Kits.PhoneInfo.getIMEI(this);
        String deviceId = Kits.PhoneInfo.getDeviceId(this);

        String path = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "sign.csr";
        File file = new File(path);
        boolean hadPojie = SharedPref.getInstance(this).getBoolean("pojie", false);
        if (file.exists()) {
            if (!hadPojie) {
                SharedPref.getInstance(this).putBoolean("pojie", true);
                file.delete();
            }
        } else {
            S.sign();
        }
        Intent intent = new Intent();
        ComponentName cn = new ComponentName("com.yanxw.vocsreader", "com.yanxw.vocsreader.MainActivity");
        intent.setComponent(cn);
        try {
            startActivity(intent);
        } catch (Exception ex) {
//                showToast("请先安装老版本软件");
            getP().install();
        }
    }


    public void setCurrentDevice(BluetoothInfo info) {
        GlobalPoolApplication.instance.bluetoothInfo = info;
        new connSocketTask().execute(info.getMac());
    }

    //----------------
    /*多线程处理(建立蓝牙设备的串行通信连接)*/
    private class connSocketTask extends AsyncTask<String, String, Integer> {
        /**
         * 常量:连接建立失败
         */
        private static final int CONN_FAIL = 0x01;
        /**
         * 常量:连接建立成功
         */
        private static final int CONN_SUCCESS = 0x02;

        /**
         * 线程启动初始化操作
         */
        @Override
        public void onPreExecute() {
            /*定义进程对话框*/
        }

        @Override
        protected Integer doInBackground(String... arg0) {
            if (GlobalPoolApplication.instance.createConn(arg0[0]))
                return CONN_SUCCESS; //建立成功
            else
                return CONN_FAIL; //建立失败
        }

        /**
         * 阻塞任务执行完后的清理工作
         */
        @Override
        public void onPostExecute(Integer result) {
            if (CONN_SUCCESS == result) {    //通信连接建立成功
                blueStatusTv.setText("已连接");
            }
        }
    }

    @Override
    public int getTitleLayoutResId() {
        return super.getTitleLayoutResId();
    }


    private void toBackUpDatas() {
        SubmitTipDialog submitTipDialog = new SubmitTipDialog(this, new SubmitTipDialog.SlectClickListener() {
            @Override
            public void submitClick() {

            }

            @Override
            public void cancelClick() {

            }
        });
        submitTipDialog.display("温馨提示", "是否备份以后数据", "否", "是");

    }

    public void showLoading(int visibility) {
        loadingTv.setVisibility(visibility);
    }

    public void showLoading(String loadMessage) {
        loadingTv.setText(loadMessage);
    }
}

